import os

from django.shortcuts import render
from io import BytesIO
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse, HttpResponseRedirect
from django.http import JsonResponse
import django.utils.timezone as timezone

from .interface import Iden
from .models import Teacher, Administrator, Student, log, Class, databaseInfo
from models import operate_log

@csrf_exempt
def accountShow(request):
    tchInfo = Teacher.objects.all()
    adminInfo = Administrator.objects.all()
    stuInfo = Student.objects.all()
    return render(request, 'AccountManage.html', {'tch': tchInfo, 'admin': adminInfo, 'stu': stuInfo})


@csrf_exempt
def accountDel(request):
    res = {}
    if request.method == 'POST':
        acc = request.POST.get('account')
        name = request.POST.get('name')
        iden = request.POST.get('iden')
        if acc == request.session['account'] and iden == request.session['iden']:
            res['status'] = 500
            return JsonResponse(res)
        if iden == 'teacher':
            operate_log.delete(request, "删除"+name+"老师", "删除")
            Teacher.objects.filter(Account=acc).delete()
            Class.objects.filter(tch_account=acc).delete()
            res['status'] = 200
        elif iden == 'student':
            operate_log.delete(request, "删除"+name+"同学", "删除")
            Student.objects.filter(Account=acc).delete()
            res['status'] = 200
        else:
            operate_log.delete(request, "删除" + name + "管理员", "删除")
            Administrator.objects.filter(Account=acc).delete()
            res['status'] = 200
        return JsonResponse(res)
    else:
        res['status'] = 403
        return JsonResponse(res)


@csrf_exempt
def logShow(request):
    logInfo = log.objects.all().order_by('-id')
    return render(request, 'log.html', {'logInfo': logInfo})

@csrf_exempt
def modelShow(request):
    return render(request, 'changeModel.html')

@csrf_exempt
def databaseShow(request):
    db_info = databaseInfo.objects.all()
    return render(request, 'DatabaseManage.html', {'db_info': db_info})

@csrf_exempt
def databaseBackup(request):
    res = {}
    if request.method == 'POST':
        db_key = "123456"  # 数据库密码
        db_host = "localhost"
        db_database_name = "xsgl"
        url = request.POST.get("backup")
        name = request.session['name']
        db_path = "./media/" + str(url)
        if url is not None:
            obj = databaseInfo(date=timezone.now(), path=db_path)
            obj.save()
            os.system("mysqldump -u root -h%s -p%s %s > %s.sql" % (db_host, db_key, db_database_name, db_path))
            operate_log.backup(request, name+"备份数据库", "备份")
        res['status'] = 200
        return JsonResponse(res)
    else:
        res['status'] = 500
        return JsonResponse(res)


@csrf_exempt
def databaseRestore(request):
    res = {}
    if request.method == 'POST':
        db_key = "123456"  # 1.sql 数据库密码
        db_host = "localhost"
        db_database_name = "xsgl"
        path = request.POST.get("restore")
        db_path = str(path)
        name = request.session['name']
        filename = db_path.split('/')[2]
        if db_path is not None:
            os.system("mysqldump -u root -h%s -p%s %s < %s.sql" % (db_host, db_key, db_database_name, db_path))
            operate_log.rollback(request, name + "恢复数据库" + filename, "恢复")
        res['status'] = 200
        return JsonResponse(res)
    else:
        res['status'] = 500
        return JsonResponse(res)
